#include "http_request.h"
#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;

namespace vmon_web
{

HttpRequest::HttpRequest()
    :m_contentLength(0)
{
}

HttpRequest::~HttpRequest()
{
}

string HttpRequest::getValue(const string& key) const
{
    map<string, string>::const_iterator iter = m_keywords.find(key);
    if (iter != m_keywords.end()) {
        return iter->second;
    }
    return string();
}

void HttpRequest::setValue(const string& key, const string& value)
{
    m_keywords[key] = value;
}

void HttpRequest::setValue(const string& str)
{
    unsigned int colon = str.find(':');
    if (colon != str.npos) {
        string key = str.substr(0, colon);
        unsigned int i = colon + 1;
        while (i < str.length() && str[i] == ' ') {
            i++;
        }
        if (i > colon + 1)
            i--;
        unsigned int j = str.find('\r');
        if (j == str.npos) {
            j = str.find('\n');
        }

        string value = str.substr(i, j - i);
        setValue(key, value);
    }
}

unsigned int HttpRequest::getContentLength()
{
    if (m_contentLength == 0) {
        string s = getValue("Content-Length");
        m_contentLength = strtoul(s.c_str(), 0, 0);
    }
    return m_contentLength;
}

vector<unsigned char>& HttpRequest::getContent()
{
    return m_content;
}

void HttpRequest::addContentByte(unsigned char c)
{
    m_content.push_back(c);
}


}
